// import { asyncRoutes, VenueRoutes } from '@/router/async'
import { asyncRoutes } from '@/router/async'
import router from '@/router'
import { slidebar } from '@/api'
import { removeToken } from '@/utils/auth'
// import Ls from '@/utils/storage'

// const ls = new Ls()

const state = {
  routes: []
}

const mutations = {
  CHANGE_ROUTES: (state, data) => {
    state.routes = data
  }
}

function checkRoutes(route, route_) {
  for (let i = 0; i <= route.length; i++) {
    if (route[i] && route[i].meta && route[i].meta.serveName) {
      const { serveName } = route[i].meta
      if (route_[serveName]) {
        route[i].meta.buttons = route_[serveName]
        route[i].meta.hidden = route[i].hidden
      } else {
        console.log('删除', route[i].meta)
        route.splice(i, 1)
        i--
      }
      if (route[i] && route[i].children) {
        checkRoutes(route[i].children, route_)
      }
    } else {
      if (route[i] && route[i].meta) {
        route[i].meta.hidden = route[i].hidden
      }
      if (route[i] && route[i].children) {
        checkRoutes(route[i].children, route_)
      }
    }
  }
  return route
}
function paixu(arr, arrb) {
  const arrs = []
  arrs.push(arr[0])
  arrs.push(arr[1])
  arrb.forEach(a => {
    arr.forEach(b => {
      if ((b.meta && b.meta.serveName && a === b.meta.serveName)) {
        arrs.push(b)
      }
    })
  })
  return arrs
}

const actions = {
  changeRoutes({ commit, dispatch }, data) {
    const shopId = localStorage.getItem('shopId')
    const userId = sessionStorage.getItem('userId')
    if ((shopId && shopId !== 'null' && shopId !== 'undefined') && (userId && userId !== 'null' && userId !== 'undefined')) {
      slidebar({ param: { workType: 1 }}).then(res => {
        if (res.errorCode === '000000') {
          let allRoutes = []
          allRoutes = checkRoutes(asyncRoutes, res.record)
          // 动态添加路由
          let arr = []
          arr = paixu(allRoutes, res.record['FIRST_MENU'])
          router.addRoutes(arr)
          commit('CHANGE_ROUTES', arr)
          // 跳转到当前路由 或 '/'
          // router.push(sessionStorage.getItem('activeRoute') || '/')
          // 错误路由重定向到 404
          router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
          dispatch('tagsView/delAllViews', null, { root: true })
          setInterval(() => {
            slidebar({ param: { workType: 1 }}).then(() => { })
          }, 3900000)
        } else {
          removeToken()
          router.replace(`/login`)
        }
      }).catch(err => {
        console.log('changeRoutes', err)
      })
    } else {
      removeToken()
      router.replace(`/login`)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

